#include "comm.hpp"

int main()
{
    // 1.获取唯一标识同一共享内存的key值
    key_t k = ftok(PATH_NAME, PROJ_ID);
    assert(k != -1);
    Log("get key success", Debug) << "[" << TransKeyToHex(k) << "]" << endl;

    // 2.获取一个共享内存
    int shmid = shmget(k, SHMSIZE, 0); // 获取server已经创建好的共享内存
    Log("get shm success", Debug) << "[" << shmid << "]" << endl;

    // 3.挂接共享内存到地址空间上（建立映射）
    char *shmaddr = (char *)shmat(shmid, nullptr, 0);
    assert(shmaddr != nullptr);
    Log("attach shm success", Debug) << endl;

    // 使用共享内存
    // 相当于使用malloc得来的char buffer[]
    // 1:
    // char c = 'a';
    // for (c = 'a'; c <= 'z'; c++)
    // {
    //     // snprintf(shmaddr, SHMSIZE - 1, "hello,mypid[%d][%c]", getpid(), c);
    //     shmaddr[c - 'a'] = c;
    //     shmaddr[c - 'a' + 1] = '\0';
    //     sleep(1); // 每隔一秒刷新一次数据
    // }
    // strcpy(shmaddr, "quit");

    // 2:
    int fd = openFIFO(WRITE);
    while (true)
    {
        ssize_t s = read(0, shmaddr, SHMSIZE - 1);
        if (s > 0)
        {
            shmaddr[s - 1] = '\0'; // 去掉输入之后回车的\n
            signal(fd);
            if (strcmp(shmaddr, "quit") == 0)
                break;
        }
    }
    closeFIFO(fd);

    // 4.去关联共享内存
    int n = shmdt(shmaddr);
    assert(n != -1);
    Log("dettach shm success", Debug) << endl;

    // 共享内存由创建者删

    return 0;
}
